﻿using System;
using System.Net;
using System.Threading;

namespace QDP.Platform.IO
{
    public class Downloader
    {
        public event EventHandler<FileDownloadCompleteEventArgs> DownloadCompleted;
        public event EventHandler<FileDownloadProgressEventArgs> DownloadProgressChanged;
        public event EventHandler<FileDownloadErrorAccured> ErrorAccured;
        public void DownloadFile(string xapName)
        {
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.OnDownloadProgressChanged);
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(this.OnOpenReadCompleted);

            if (xapName.StartsWith("http"))
            {
                client.OpenReadAsync(new Uri(xapName));
            }
            else
            {
                string baseUrl = client.BaseAddress.Remove(client.BaseAddress.LastIndexOf("/") + 1);
                client.OpenReadAsync(new Uri(baseUrl + xapName));
            }
            //client.OpenReadAsync(new Uri(xapName + "?" + DateTime.Now.Ticks.ToString(), UriKind.Relative));
        }

        private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (this.DownloadProgressChanged != null)
            {
                this.DownloadProgressChanged(this, new FileDownloadProgressEventArgs(e.ProgressPercentage));
            }
        }

        private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (this.ErrorAccured != null)
                {
                    this.ErrorAccured(this, new FileDownloadErrorAccured { Exception = e.Error });
                }
            }
            else if (this.DownloadCompleted != null)
            {
                this.DownloadCompleted(this, new FileDownloadCompleteEventArgs(e.Result));
            }
        }
    }
}